<template>
  <div class="login-container">
    <div class="login-wrapper">
      <div class="login-card">
        <div class="login-header">
          <h2 class="login-title">
            <i class="bi bi-shield-lock-fill me-2"></i>
            用户登录
          </h2>
          <p class="login-subtitle">欢迎回到 NestJS 学习项目</p>
        </div>

        <!-- 错误和成功消息 -->
        <div v-if="errorMessage" class="alert alert-danger mb-3" role="alert">
          <i class="bi bi-exclamation-triangle-fill me-2"></i>
          {{ errorMessage }}
        </div>

        <div v-if="successMessage" class="alert alert-success mb-3" role="alert">
          <i class="bi bi-check-circle-fill me-2"></i>
          {{ successMessage }}
        </div>

        <form @submit.prevent="handleLogin" class="login-form">
          <div class="mb-3">
            <label for="usernameOrEmail" class="form-label">
              <i class="bi bi-person-fill me-1"></i>
              用户名或邮箱
            </label>
            <input
              id="usernameOrEmail"
              v-model="loginForm.usernameOrEmail"
              type="text"
              class="form-control"
              :class="{ 'is-invalid': errors.usernameOrEmail }"
              placeholder="请输入用户名或邮箱"
              required
            />
            <div v-if="errors.usernameOrEmail" class="invalid-feedback">
              {{ errors.usernameOrEmail }}
            </div>
          </div>

          <div class="mb-3">
            <label for="password" class="form-label">
              <i class="bi bi-lock-fill me-1"></i>
              密码
            </label>
            <div class="password-input-wrapper">
              <input
                id="password"
                v-model="loginForm.password"
                :type="showPassword ? 'text' : 'password'"
                class="form-control"
                :class="{ 'is-invalid': errors.password }"
                placeholder="请输入密码"
                required
              />
              <button
                type="button"
                class="password-toggle-btn"
                @click="togglePassword"
                :title="showPassword ? '隐藏密码' : '显示密码'"
              >
                <i :class="showPassword ? 'bi bi-eye-slash-fill' : 'bi bi-eye-fill'"></i>
              </button>
            </div>
            <div v-if="errors.password" class="invalid-feedback">
              {{ errors.password }}
            </div>
          </div>

          <div class="mb-3 form-check">
            <input id="rememberMe" v-model="loginForm.rememberMe" type="checkbox" class="form-check-input" />
            <label for="rememberMe" class="form-check-label"> 记住我 </label>
          </div>

          <button type="submit" class="btn btn-primary btn-login" :disabled="isLoading">
            <span v-if="isLoading" class="spinner-border spinner-border-sm me-2"></span>
            <i v-else class="bi bi-box-arrow-in-right me-2"></i>
            {{ isLoading ? "登录中..." : "登录" }}
          </button>

          <div class="login-links">
            <a href="#" class="forgot-password-link">忘记密码？</a>
            <span class="divider">|</span>
            <a @click.prevent="goToRegister" class="register-link">注册新账户</a>
          </div>
        </form>
      </div>

      <div class="login-footer">
        <p>&copy; 2025 NestJS Learning Project. Built with Vue 3 + Bootstrap 5</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useAuthStore } from "@/stores/auth";
import type { LoginForm, LoginErrors } from "@/types/auth";

defineOptions({
  name: "LoginView",
});

const router = useRouter();
const authStore = useAuthStore();

// 响应式数据
const isLoading = ref(false);
const showPassword = ref(false);
const errorMessage = ref("");
const successMessage = ref("");

const loginForm = reactive<LoginForm>({
  usernameOrEmail: "",
  password: "",
  rememberMe: false,
});

const errors = reactive<LoginErrors>({
  usernameOrEmail: "",
  password: "",
});

// 初始化
onMounted(() => {
  // 如果已经登录，直接跳转到首页
  if (authStore.isAuthenticated) {
    router.push("/");
  }
});

// 方法
const togglePassword = () => {
  showPassword.value = !showPassword.value;
};

const validateForm = (): boolean => {
  // 清空之前的错误
  errors.usernameOrEmail = "";
  errors.password = "";

  let isValid = true;

  // 验证用户名
  if (!loginForm.usernameOrEmail.trim()) {
    errors.usernameOrEmail = "请输入用户名或邮箱";
    isValid = false;
  } else if (loginForm.usernameOrEmail.length < 2) {
    errors.usernameOrEmail = "用户名或邮箱至少需要2个字符";
    isValid = false;
  }

  // 验证密码
  if (!loginForm.password) {
    errors.password = "请输入密码";
    isValid = false;
  } else if (loginForm.password.length < 6) {
    errors.password = "密码至少需要6个字符";
    isValid = false;
  }

  return isValid;
};

const handleLogin = async () => {
  // 清空之前的消息
  errorMessage.value = "";
  successMessage.value = "";

  if (!validateForm()) {
    return;
  }

  isLoading.value = true;

  try {
    const result = await authStore.signin({
      usernameOrEmail: loginForm.usernameOrEmail,
      password: loginForm.password,
    });

    if (result.success) {
      successMessage.value = result.message;

      // 登录成功后跳转到首页
      setTimeout(() => {
        router.push("/");
      }, 1000);
    } else {
      errorMessage.value = result.message;
    }
  } catch (error: any) {
    console.error("登录失败:", error);
    errorMessage.value = error.message || "登录失败，请稍后重试";
  } finally {
    isLoading.value = false;
  }
};

// 跳转到注册页面
const goToRegister = () => {
  router.push("/register");
};
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem 1rem;
}

.login-wrapper {
  width: 100%;
  max-width: 400px;
}

.login-card {
  background: white;
  border-radius: 1rem;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  padding: 2.5rem;
  margin-bottom: 2rem;
}

.login-header {
  text-align: center;
  margin-bottom: 2rem;
}

.login-title {
  color: #333;
  font-weight: 700;
  margin-bottom: 0.5rem;
  font-size: 1.75rem;
}

.login-subtitle {
  color: #666;
  margin-bottom: 0;
  font-size: 0.95rem;
}

.login-form .form-label {
  font-weight: 600;
  color: #333;
  margin-bottom: 0.5rem;
}

.form-control {
  border-radius: 0.5rem;
  border: 2px solid #e9ecef;
  padding: 0.75rem 1rem;
  font-size: 1rem;
  transition: all 0.3s ease;
}

.form-control:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
}

.password-input-wrapper {
  position: relative;
}

.password-toggle-btn {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  padding: 0;
  font-size: 1.1rem;
  transition: color 0.2s ease;
}

.password-toggle-btn:hover {
  color: #333;
}

.form-check {
  margin-bottom: 1.5rem;
}

.form-check-label {
  color: #666;
  font-size: 0.9rem;
}

.btn-login {
  width: 100%;
  padding: 0.75rem;
  font-size: 1.1rem;
  font-weight: 600;
  border-radius: 0.5rem;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  transition: all 0.3s ease;
}

.btn-login:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.btn-login:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.login-links {
  text-align: center;
  margin-top: 1.5rem;
  font-size: 0.9rem;
}

.forgot-password-link,
.register-link {
  color: #667eea;
  text-decoration: none;
  cursor: pointer;
  transition: color 0.2s ease;
}

.forgot-password-link:hover,
.register-link:hover {
  color: #764ba2;
}

.divider {
  margin: 0 0.5rem;
  color: #ccc;
}

.login-footer {
  text-align: center;
  color: rgba(255, 255, 255, 0.8);
  font-size: 0.85rem;
}

.login-footer p {
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-container {
    padding: 1rem 0.5rem;
  }

  .login-card {
    padding: 2rem 1.5rem;
  }

  .login-title {
    font-size: 1.5rem;
  }
}

/* 动画效果 */
.login-card {
  animation: slideUp 0.6s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.spinner-border-sm {
  width: 1rem;
  height: 1rem;
}
</style>
